#!/bin/bash

### Constants
CHECK_PKG_INSTALLED='dpkg-query -s'
scriptDir="/opt/pivpn"

### Functions
err() {
  echo "[$(date +'%Y-%m-%dT%H:%M:%S%z')]: $*" >&2
}

uninstallServer() {
  ${SUDO} "${scriptDir}/uninstall.sh"
  exit "${?}"
}

backup() {
  ${SUDO} "${scriptDir}/backup.sh"
  exit "${?}"
}

showHelp() {
  echo "::: To pass off to the pivpn command for each protocol"
  echo ":::"
  echo "::: Usage: pivpn wg  <command> [option]"
  echo "::: Usage: pivpn ovpn <command> [option]"
  echo ":::"
  echo ":::  -h,  help             Show this help dialog"
  echo ":::  -u,  uninstall        Uninstall pivpn from your system!"
  echo ":::  -bk, backup           Backup VPN configs and user profiles"
  exit 0
}

### Script
# Must be root to use this tool
if [[ "${EUID}" -ne 0 ]]; then
  if ${CHECK_PKG_INSTALLED} sudo &> /dev/null; then
    export SUDO="sudo"
  else
    err "::: Please install sudo or run this as root."
    exit 1
  fi
fi

if grep -qsEe "^NAME\=['\"]?Alpine[a-zA-Z ]*['\"]?$" /etc/os-release; then
  CHECK_PKG_INSTALLED='apk --no-cache info -e'
fi

if [[ "$#" == 0 ]]; then
  showHelp
fi

# Handle redirecting to specific functions based on arguments
case "${1}" in
  wg)
    "${scriptDir}/wireguard/pivpn.sh" "${@:2}"
    ;;
  ovpn)
    "${scriptDir}/openvpn/pivpn.sh" "${@:2}"
    ;;
  "-h" | "help")
    showHelp
    ;;
  "-u" | "uninstall")
    uninstallServer
    ;;
  "-bk" | "backup")
    backup
    ;;
  *)
    showHelp
    ;;
esac
